<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const loading = ref(false)
const showRegister = ref(false)

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: ''
})

// 登录表单规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ]
}

// 注册表单规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const loginFormRef = ref(null)
const registerFormRef = ref(null)

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const success = await authStore.login(loginForm)
        if (success) {
          ElMessage.success('登录成功')
          
          // 检查是否有重定向地址
          const redirectPath = route.query.redirect || '/'
          router.push(redirectPath)
        }
      } catch (error) {
        ElMessage.error(error.message || '登录失败，请检查账号和密码')
      } finally {
        loading.value = false
      }
    }
  })
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return

  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const success = await authStore.register(registerForm)
        if (success) {
          ElMessage.success('注册成功，请登录')
          showRegister.value = false
          loginForm.username = registerForm.username
          loginForm.password = ''
        }
      } catch (error) {
        ElMessage.error(error.message || '注册失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 切换到注册页面
const toggleRegister = () => {
  showRegister.value = !showRegister.value
  if (loginFormRef.value) loginFormRef.value.resetFields()
  if (registerFormRef.value) registerFormRef.value.resetFields()
}
</script>

<template>
  <div class="login-container">
    <div class="login-content">
      <!-- Logo -->
      <div class="logo-section">
        <div class="logo-box">
          <h1 class="system-name">RPA管理系统</h1>
          <p class="system-desc">流程自动化一站式解决方案</p>
        </div>
      </div>

      <!-- 登录表单 -->
      <div v-if="!showRegister" class="form-section">
        <h2>登录</h2>
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-position="top"
          class="login-form"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              prefix-icon="User"
              placeholder="用户名"
              :clearable="true"
            >
              <template #prefix>
                <el-icon><user /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              prefix-icon="Lock"
              placeholder="密码"
              type="password"
              show-password
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <el-icon><lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <div class="form-action">
            <el-button type="primary" class="login-button" :loading="loading" @click="handleLogin">登录</el-button>
          </div>
          <div class="form-options">
            <el-button link type="primary" @click="toggleRegister">没有账号？立即注册</el-button>
          </div>
        </el-form>
      </div>

      <!-- 注册表单 -->
      <div v-else class="form-section">
        <h2>注册</h2>
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          label-position="top"
          class="register-form"
        >
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              prefix-icon="User"
              placeholder="用户名"
              :clearable="true"
            >
              <template #prefix>
                <el-icon><user /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              prefix-icon="Lock"
              placeholder="密码"
              type="password"
              show-password
            >
              <template #prefix>
                <el-icon><lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              prefix-icon="Lock"
              placeholder="确认密码"
              type="password"
              show-password
            >
              <template #prefix>
                <el-icon><key /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input
              v-model="registerForm.email"
              prefix-icon="Message"
              placeholder="邮箱"
              :clearable="true"
            >
              <template #prefix>
                <el-icon><i class="el-icon-message"></i></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <div class="form-action">
            <el-button type="primary" class="register-button" :loading="loading" @click="handleRegister">注册</el-button>
          </div>
          <div class="form-options">
            <el-button link type="primary" @click="toggleRegister">已有账号？返回登录</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #e3f0ff 0%, #d4e5f7 100%);
  position: fixed;
  top: 0;
  left: 0;
}

.login-content {
  display: flex;
  max-width: 900px;
  min-height: 500px;
  width: 90%;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(44, 62, 80, 0.1);
  overflow: hidden;
}

.logo-section {
  flex: 1;
  background: linear-gradient(135deg, #1890FF 0%, #0C63E7 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.logo-box {
  text-align: center;
}

.system-name {
  font-size: 2.5rem;
  font-weight: 600;
  margin-bottom: 16px;
}

.system-desc {
  font-size: 1.1rem;
  opacity: 0.9;
  margin-bottom: 20px;
}

.form-section {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;
}

.form-section h2 {
  font-size: 1.8rem;
  margin-bottom: 24px;
  color: #2C3E50;
  text-align: center;
}

.login-form, .register-form {
  width: 100%;
}

.el-input {
  --el-input-height: 42px;
}

.form-action {
  margin-top: 16px;
}

.login-button, .register-button {
  width: 100%;
  padding: 12px;
  height: auto;
  font-size: 1rem;
  background-color: #1890FF;
  border-color: #1890FF;
}

.login-button:hover, .register-button:hover {
  background-color: #0C63E7;
  border-color: #0C63E7;
}

.form-options {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .login-content {
    flex-direction: column;
    height: auto;
  }
  
  .logo-section {
    padding: 20px;
  }
  
  .system-name {
    font-size: 1.8rem;
  }
  
  .form-section {
    padding: 20px;
  }
}
</style> 